package com.fanrenqiji.modules.sys.web;

import com.fanrenqiji.common.config.GlobalSetting;
import com.fanrenqiji.common.persistence.Page;
import com.fanrenqiji.common.web.BaseController;
import com.fanrenqiji.modules.sys.entity.Dict;
import com.fanrenqiji.modules.sys.service.DictService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author lijian E-mail:ljz0721cx@163.com
 * @version 创建时间：2015年2月6日 下午2:14:36
 * @description 字典控制器类
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/dict")
public class DictController extends BaseController {

	@Autowired
	private DictService dictService;

	@ModelAttribute("dict")
	public Dict getDict(@RequestParam(required = false) Long id) {
		if (id != null) {
			return dictService.findOne(id);
		} else {
			return new Dict();
		}
	}

	/**
	 * 获得字典表的列表
	 * 
	 * @return
	 */
	@RequiresPermissions("sys:dict:view")
	@RequestMapping(value = { "list", "" })
	public String list(Dict dict, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		List<String> typeList = dictService.findTypeList();
		model.addAttribute("typeList", typeList);
		Page<Dict> page = dictService.find(new Page<Dict>(request, response),
				dict);
		model.addAttribute("page", page);
		return "modules/sys/dictList";
	}

	/**
	 * 用户添加更新字典表
	 * 
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:dict:view")
	@RequestMapping(value = "form")
	public String form(Model model, Dict dict) {
		model.addAttribute("dict", dict);
		return "modules/sys/dictForm";
	}

	/**
	 * 添加或跟新数据字典
	 * 
	 * @param dict
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:dict:edit")
	@RequestMapping(value = "save")
	public String save(Dict dict, Model model,
			RedirectAttributes redirectAttributes) {// TODO @Valid 添加后端校验
		if (!beanValidator(model, dict)) {
			return form(model, dict);
		}
		dictService.save(dict);
		addMessage(redirectAttributes, "保存字典'" + dict.getLabel() + "'成功");
		return "redirect:" + GlobalSetting.getAdminPath()
				+ "/sys/dict/?repage&type=" + dict.getType();
	}

}
